import com.jingdong.callback.JingdongCallbackSDK;
import com.jingdong.callback.model.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 京东配送回调SDK使用示例
 * 
 * @author SDK Team
 */
public class Example {
    
    public static void main(String[] args) {
        
        // 初始化SDK
        JingdongCallbackSDK sdk = new JingdongCallbackSDK.Builder()
                .developerId("your-developer-id")     // 海博技术服务平台分配的开发者ID
                .secret("your-secret")                 // 签名密钥
                .environment("test")                   // 环境: test, sandbox, prod
                .redisHost("127.0.0.1")               // Redis主机（可选，用于防重复）
                .redisPort(6379)                      // Redis端口
                .redisDatabase(0)                     // Redis数据库编号
                .enableLog(true)                      // 启用日志
                .userAgent("MyApp-JingdongSDK/1.0")   // 自定义User-Agent
                .build();
        
        try {
            // 示例1：基本状态回调
            System.out.println("=== 示例1：基本状态回调 ===");
            basicStatusCallback(sdk);
            
            System.out.println();
            
            // 示例2：包含额外参数的状态回调
            System.out.println("=== 示例2：包含额外参数的状态回调 ===");
            statusCallbackWithExtraParams(sdk);
            
            System.out.println();
            
            // 示例3：取消订单回调
            System.out.println("=== 示例3：取消订单回调 ===");
            cancelOrderCallback(sdk);
            
            System.out.println();
            
            // 示例4：转单回调
            System.out.println("=== 示例4：转单回调 ===");
            transferOrderCallback(sdk);
            
            System.out.println();
            
            // 示例5：包含费用信息的完成回调
            System.out.println("=== 示例5：包含费用信息的完成回调 ===");
            completedOrderWithFeeCallback(sdk);
            
            System.out.println();
            
            // 示例6：连通性测试
            System.out.println("=== 示例6：连通性测试 ===");
            connectivityTest(sdk);
            
            System.out.println();
            
            // 示例7：状态转换工具
            System.out.println("=== 示例7：状态转换工具 ===");
            statusConversionDemo();
            
            System.out.println();
            
            // 示例8：取消原因码工具
            System.out.println("=== 示例8：取消原因码工具 ===");
            cancelReasonCodeDemo();
            
        } finally {
            // 关闭SDK资源
            sdk.close();
        }
        
        System.out.println("\n示例运行完成！");
    }
    
    /**
     * 示例1：基本状态回调
     */
    private static void basicStatusCallback(JingdongCallbackSDK sdk) {
        // 创建订单对象
        Order order = new Order();
        order.setId(12345L);
        order.setPlatformOrderNo("JD202312345678");
        order.setOrderNo("ORDER_20231201_001");
        order.setJdStoreId("STORE_001");
        order.setCarrierMerchantId("HBT_JZD");
        order.setRiderId(1001L);
        order.setRiderName("张三");
        order.setRiderPhone("13800138000");
        order.setRiderLng(116.397128);
        order.setRiderLat(39.916527);
        
        // 发送"已接单"状态回调
        CallbackResult result = sdk.sendStatusCallback(order, 20);
        
        if (result.isSuccess()) {
            System.out.println("✅ 状态回调发送成功");
            System.out.println("响应数据: " + result.getData());
        } else {
            System.out.println("❌ 状态回调发送失败: " + result.getMessage());
        }
    }
    
    /**
     * 示例2：包含额外参数的状态回调
     */
    private static void statusCallbackWithExtraParams(JingdongCallbackSDK sdk) {
        Order order = createSampleOrder();
        
        Map<String, Object> extraParams = new HashMap<>();
        extraParams.put("riderLng", 116.407526);   // 实时骑手经度
        extraParams.put("riderLat", 39.904030);    // 实时骑手纬度
        
        // 订单图片
        Map<String, Object> orderImages = new HashMap<>();
        orderImages.put("pickup", new String[]{"https://example.com/image1.jpg", "https://example.com/image2.jpg"});
        extraParams.put("orderImages", orderImages);
        
        // 发送"已取货"状态回调
        CallbackResult result = sdk.sendStatusCallback(order, 30, extraParams);
        
        if (result.isSuccess()) {
            System.out.println("✅ 已取货状态回调发送成功");
        } else {
            System.out.println("❌ 已取货状态回调发送失败: " + result.getMessage());
        }
    }
    
    /**
     * 示例3：取消订单回调
     */
    private static void cancelOrderCallback(JingdongCallbackSDK sdk) {
        Order order = createSampleOrder();
        
        Map<String, Object> cancelParams = new HashMap<>();
        cancelParams.put("cancelReasonCode", JingdongCallbackSDK.getCancelReasonCode("CUSTOMER"));
        cancelParams.put("cancelReasonDesc", JingdongCallbackSDK.getCancelReasonDesc("CUSTOMER", "用户临时有事"));
        cancelParams.put("cancelFee", 5.00);
        
        // 发送取消状态回调
        CallbackResult result = sdk.sendStatusCallback(order, 99, cancelParams);
        
        if (result.isSuccess()) {
            System.out.println("✅ 取消订单回调发送成功");
        } else {
            System.out.println("❌ 取消订单回调发送失败: " + result.getMessage());
        }
    }
    
    /**
     * 示例4：转单回调
     */
    private static void transferOrderCallback(JingdongCallbackSDK sdk) {
        Order order = createSampleOrder();
        
        Map<String, Object> transferParams = new HashMap<>();
        transferParams.put("isTransfer", true);
        transferParams.put("oldRiderId", 1001L);
        transferParams.put("newRiderId", 1002L);
        transferParams.put("newRiderName", "李四");
        transferParams.put("newRiderPhone", "13900139000");
        transferParams.put("transferReason", "骑手临时有事转单");
        
        // 发送转单后的"已接单"状态回调
        CallbackResult result = sdk.sendStatusCallback(order, 20, transferParams);
        
        if (result.isSuccess()) {
            System.out.println("✅ 转单回调发送成功");
        } else {
            System.out.println("❌ 转单回调发送失败: " + result.getMessage());
        }
    }
    
    /**
     * 示例5：包含费用信息的完成回调
     */
    private static void completedOrderWithFeeCallback(JingdongCallbackSDK sdk) {
        Order order = createSampleOrder();
        
        // 设置费用信息
        OrderFee fee = new OrderFee();
        fee.setActualAmount(new BigDecimal("15.80"));
        fee.setTollFee(new BigDecimal("2.00"));
        fee.setWaitingFee(new BigDecimal("1.00"));
        fee.setParkingFee(new BigDecimal("0.50"));
        order.setFee(fee);
        
        // 发送"已送达"状态回调
        CallbackResult result = sdk.sendStatusCallback(order, 50);
        
        if (result.isSuccess()) {
            System.out.println("✅ 已送达回调发送成功");
        } else {
            System.out.println("❌ 已送达回调发送失败: " + result.getMessage());
        }
    }
    
    /**
     * 示例6：连通性测试
     */
    private static void connectivityTest(JingdongCallbackSDK sdk) {
        ConnectivityResult connectivity = sdk.testConnectivity();
        
        // DNS解析测试
        ConnectivityResult.DnsResult dns = connectivity.getDns();
        System.out.println("DNS解析: " + (dns.isSuccess() ? "✅ 成功" : "❌ 失败"));
        System.out.println("  主机: " + dns.getHost() + " => " + dns.getIp());
        
        // 端口连通性测试
        ConnectivityResult.PortResult port = connectivity.getPort();
        System.out.println("端口连通: " + (port.isSuccess() ? "✅ 成功" : "❌ 失败"));
        System.out.println("  端口: " + port.getHost() + ":" + port.getPort());
        if (!port.isSuccess() && port.getError() != null) {
            System.out.println("  错误: " + port.getError());
        }
        
        // HTTP请求测试
        ConnectivityResult.HttpResult http = connectivity.getHttp();
        System.out.println("HTTP请求: " + (http.isSuccess() ? "✅ 成功" : "❌ 失败"));
        System.out.println("  状态码: " + http.getHttpCode());
        if (!http.isSuccess() && http.getError() != null) {
            System.out.println("  错误: " + http.getError());
        }
    }
    
    /**
     * 示例7：状态转换工具
     */
    private static void statusConversionDemo() {
        String[] localStatuses = {"0", "10", "20", "25", "30", "40", "50", "99"};
        
        for (String localStatus : localStatuses) {
            int jdStatus = JingdongCallbackSDK.convertLocalStatusToJingdongStatus(localStatus);
            System.out.println("本地状态 " + localStatus + " => 京东状态 " + jdStatus);
        }
    }
    
    /**
     * 示例8：取消原因码工具
     */
    private static void cancelReasonCodeDemo() {
        String[] roles = {"ADMIN", "MERCHANT", "CUSTOMER", "SYSTEM", "RIDER", "CARRIER"};
        
        for (String role : roles) {
            int reasonCode = JingdongCallbackSDK.getCancelReasonCode(role);
            String reasonDesc = JingdongCallbackSDK.getCancelReasonDesc(role);
            System.out.println("角色 " + role + " => 取消码 " + reasonCode + " (" + reasonDesc + ")");
        }
    }
    
    /**
     * 创建示例订单
     */
    private static Order createSampleOrder() {
        Order order = new Order();
        order.setId(12345L);
        order.setPlatformOrderNo("JD202312345678");
        order.setOrderNo("ORDER_20231201_001");
        order.setJdStoreId("STORE_001");
        order.setCarrierMerchantId("HBT_JZD");
        order.setRiderId(1001L);
        order.setRiderName("张三");
        order.setRiderPhone("13800138000");
        order.setRiderLng(116.397128);
        order.setRiderLat(39.916527);
        return order;
    }
}
